package com.stephenone.zhdaily.homepage;

import android.content.ContentUris;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.stephenone.zhdaily.R;
import com.stephenone.zhdaily.ScrollChildSwipeRefreshLayout;
import com.stephenone.zhdaily.data.bean.Footer;
import com.stephenone.zhdaily.data.bean.News;
import com.stephenone.zhdaily.data.bean.Story;
import com.stephenone.zhdaily.data.bean.TopStories;
import com.stephenone.zhdaily.homepage.adapter.DateViewBinder;
import com.stephenone.zhdaily.homepage.adapter.FooterViewBinder;
import com.stephenone.zhdaily.homepage.adapter.HeaderViewBinder;
import com.stephenone.zhdaily.homepage.adapter.StoryViewBinder;
import com.stephenone.zhdaily.uitl.RecyclerViewLoadMoreListener;
import com.stephenone.zhdaily.uitl.TimeUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;

public class HomepageFragment extends Fragment implements HomepageContract.View{
    private static final String TAG = HomepageFragment.class.getSimpleName();
    private HomepageContract.Presenter mPresenter;
    private RecyclerView mRecyclerView;

    private Items items;
    private MultiTypeAdapter mAdapter;

    private SwipeRefreshLayout mSwipeRefreshLayout;
    private String mCurrentDate;
    private boolean isLoading;

    public HomepageFragment() {
    }

    public static HomepageFragment newInstance() {
        HomepageFragment fragment = new HomepageFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e(TAG, "onCreate: ");
        if (getArguments() != null) {
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Log.e(TAG, "onCreateView: ");
        View contentView = inflater.inflate(R.layout.fragment_homepage, container, false);
        mSwipeRefreshLayout = contentView.findViewById(R.id.swipe_refresh_layout);
        mSwipeRefreshLayout.setOnRefreshListener( () -> {
                mPresenter.loadNews(true);
        });
        mRecyclerView = contentView.findViewById(R.id.recyclerView);
         /* 注意：我们已经在 XML 布局中通过 app:layoutManager="LinearLayoutManager"
         * 给这个 RecyclerView 指定了 LayoutManager，因此此处无需再设置 */
//        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.addItemDecoration(new ItemGapDecoration(30));

        mRecyclerView.addOnScrollListener(new RecyclerViewLoadMoreListener() {
            @Override
            public void onLoadMore() {
                mPresenter.loadMore(TimeUtil.beforeThis(mCurrentDate));
            }
        });

        ScrollChildSwipeRefreshLayout swipeRefreshLayout = contentView.findViewById(R.id.swipe_refresh_layout);
        swipeRefreshLayout.setScrollUpChild(mRecyclerView);

        mAdapter = new MultiTypeAdapter();
        mAdapter.register(String.class, new DateViewBinder());
        mAdapter.register(Story.class,new StoryViewBinder(getActivity()));
        mAdapter.register(TopStories.class,new HeaderViewBinder(getActivity()));
        mAdapter.register(Footer.class,new FooterViewBinder());
        mRecyclerView.setAdapter(mAdapter);

        return contentView;
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.e(TAG, "onResume: ");
        // TODO: 2018/1/15
//        mViewPager.resumeAutoScroll();

        mPresenter.subscribe();

    }

    @Override
    public void onPause() {
        // TODO: 2018/1/15
//        mViewPager.pauseAutoScroll();

        mPresenter.unsubscribe();
        super.onPause();
    }

    @Override
    public void setPresenter(HomepageContract.Presenter presenter) {
        this.mPresenter = presenter;
    }

    @Override
    public void showNews(List<News> news) {
        items = new Items();

        news = resortNews(news);
        for (int i = 0; i < news.size(); i ++) {
            News news1 = news.get(i);
            if (news1.getTop_stories() != null) {
                items.add(new TopStories(news1.getTop_stories()));
            }
            items.add(news1.getDate());
            items.addAll(news1.getStories());
            if (i == news.size() - 1) {
                items.add(new Footer());
            }
            mCurrentDate = news1.getDate();
        }
        mAdapter.setItems(items);
        mAdapter.notifyDataSetChanged();
        mSwipeRefreshLayout.setRefreshing(false);
    }

    private List<News> resortNews(List<News> news) {
        List<News> news1 = new ArrayList<>();
        for (int i = 0; i < news.size(); i++) {
            if (news.get(i).getTop_stories() != null) {
                news1.add(news.get(i));
                news.remove(i);
            } else {
                continue;
            }
        }
        Collections.sort(news,(o1, o2) -> - o1.getDate().compareTo(o2.getDate()));
        for (int i = 0; i < news.size(); i++) {
            news1.add(news.get(i));
        }
        return news1;
    }

    @Override
    public void showMoreNews(News news) {

        items.remove(items.size() - 1);
        items.add(news.getDate());
        items.addAll(news.getStories());
        items.add(new Footer());
        mAdapter.notifyDataSetChanged();
        mCurrentDate = news.getDate();
    }

    @Override
    public boolean isLoading() {
        return isLoading;
    }

    @Override
    public void setLoading(boolean isLoading) {
        this.isLoading = isLoading;
    }

    @Override
    public void setLoadingIndicator(boolean active) {
        if (getView() == null) {
            return;
        }
        final SwipeRefreshLayout srl = getView().findViewById(R.id.swipe_refresh_layout);

        // Make sure setRefreshing() is called after the layout is done with everything else.
        srl.post(() -> srl.setRefreshing(active));
    }

//    @Override
//    public void onItemClick(Story story) {
//        Intent intent = new Intent(getActivity(), StoryDetailActivity.class);
//        intent.putExtra(Constants.KEY_STORY_ID,story.getId());
//        getActivity().startActivity(intent);
//    }

    class ItemGapDecoration extends RecyclerView.ItemDecoration {
        int mSpace;

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            super.getItemOffsets(outRect, view, parent, state);
//            outRect.left = mSpace;
//            outRect.right = mSpace;
            outRect.bottom = mSpace;
//            if (parent.getChildAdapterPosition(view) == 0) {
//                outRect.top = mSpace;
//            }

        }

        public ItemGapDecoration(int space) {
            this.mSpace = space;
        }
    }
}
